package com.mitcub.panda.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mitcub.panda.base.BaseQuery;
import com.mitcub.panda.base.BaseServiceImpl;
import com.mitcub.panda.entity.Admin;
import com.mitcub.panda.entity.Menu;
import com.mitcub.panda.entity.Role;
import com.mitcub.panda.mapper.MenuMapper;
import com.mitcub.panda.mapper.RoleMapper;
import com.mitcub.panda.query.MenuQuery;
import com.mitcub.panda.service.IMenuService;
import com.mitcub.panda.utils.RespResult;
import com.mitcub.panda.utils.ServletUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @项目名称: panda
 * @类名称: MenuServiceImpl
 * @类描述: 菜单 服务实现类
 * @作者: tangloong
 * @创建时间: 2021/11/2 17:22
 */
@Service
public class MenuServiceImpl extends BaseServiceImpl<MenuMapper, Menu> implements IMenuService {

    @Resource
    private MenuMapper menuMapper;
    @Resource
    private RoleMapper roleMapper;

    /**
     * 获取数据列表
     *
     * @param query 查询条件
     * @return
     */
    @Override
    public RespResult getList(BaseQuery query) {
        MenuQuery menuQuery = (MenuQuery) query;
        // 查询条件
        QueryWrapper<Menu> queryWrapper = new QueryWrapper<>();
        // 菜单名称
        if (!StringUtils.isEmpty(menuQuery.getName())) {
            queryWrapper.like("name", menuQuery.getName());
        }
        // 类型：1模块 2导航 3菜单 4节点
        if (menuQuery.getType() != null && menuQuery.getType() > 0) {
            //    queryWrapper.eq("type", menuQuery.getType());
        }
        // 是否显示：1显示 2不显示
        if (menuQuery.getStatus() != null && menuQuery.getStatus() > 0) {
            //    queryWrapper.eq("status", menuQuery.getStatus());
        }
        // 是否公共：1是 2否
        if (menuQuery.getIsPublic() != null && menuQuery.getIsPublic() > 0) {
            //    queryWrapper.eq("is_public", menuQuery.getIsPublic());
        }
        queryWrapper.eq("mark", 1);
        queryWrapper.orderByAsc("sort");

        // 查询数据
        List<Menu> menuList = menuMapper.selectList(queryWrapper);
        menuList.forEach(item ->{
            if(item.getPid() >0){
                item.setIcon("");
            }
        });

        return RespResult.success("操作成功",menuList);
    }


    @Override
    public List<Menu> getNavMenu(){
        Admin user = ServletUtils.getUserBySession();
        List<Menu> menus =  getMenuListByRoleId(user.getRoleId());
        List<Menu> menuList = new ArrayList<Menu>();
        //获取一级菜单
        for (int i = 0; i < menus.size(); i++) {
            if (menus.get(i).getPid() == 0) {
                menus.get(i).setType(0);
                menuList.add(menus.get(i));
            }
        }
        // for调用递归，循环获取所有子菜单
        for (Menu menu : menuList) {
            menu.setChildren(getChildmenus(menu.getId(), menus));
        }
        return menuList;
    }


    /**
     * 递归子菜单
     * @param id
     * @param menus
     * @return
     */
    private List<Menu> getChildmenus(long id, List<Menu> menus) {
        // 子菜单
        List<Menu> childMenus = new ArrayList<>();
        for (Menu menu : menus) {
            if (menu.getPid() != 0) {
                if (menu.getPid() == id) {
                    menu.setType(0);
                    menu.setIcon("");
                    childMenus.add(menu);
                }
            }
        }
        for (Menu menu : childMenus) {
            //数据库动态存储菜单的url,此时判断url为空的,则是节点菜单（存在子菜单）
            if (StringUtils.isBlank(menu.getUrl()) ||menu.getUrl().equals("#")) {
                // 递归调用
                menu.setChildren(getChildmenus(menu.getId(), menus));
            }
        }
        if (childMenus.size() == 0) {
            return null;
        }
        return childMenus;
    }

    /**
     * 根据角色ID获取菜单权限列表
     * @param roleId 人员ID
     * @return
     */
    @Override
    public List<Menu> getMenuListByRoleId(Integer roleId) {
        Role role = roleMapper.selectById(roleId);
        String auth = role.getAuth();
        QueryWrapper<Menu> queryWrapper = new QueryWrapper<Menu>();
        queryWrapper.eq("status",1).in("id", Arrays.asList( auth.split(",")));
        queryWrapper.eq("mark", 1);
        queryWrapper.orderByAsc("sort");
        List<Menu> menus = menuMapper.selectList(queryWrapper);
        return menus;
    }

    /**
     * 获取所有可显示的菜单
     * @param status
     * @return
     */
    @Override
    public List<Menu> getAllMenuList(int status) {
        List<Menu> menus = new ArrayList<>();
        if(status == 1) {
            menus = menuMapper.selectList(new QueryWrapper<Menu>().eq("status", status).eq("mark", 1));
        }else{
            menus = menuMapper.selectList(new QueryWrapper<Menu>());
        }
        return menus;
    }

}